package leetcode.binarytree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author huangweiyue
 * @version v1.0
 * @task 102 二叉树层序遍历 https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * @description
 * @date Created in 2021-07-05
 */
public class BinaryTreeLevelOrderTraversal {
    public static void main(String[] args) {
        //二叉树：[3,9,20,null,null,15,7],
        TreeNode root = new TreeNode(3);
        TreeNode level1Left = new TreeNode(9);
        root.left = level1Left;
        TreeNode level1Right = new TreeNode(20);
        root.right = level1Right;

        TreeNode level2Left = new TreeNode(15);
        level1Right.left = level2Left;
        TreeNode level2Right = new TreeNode(7);
        level1Right.right = level2Right;
        System.out.println(levelOrder(root));
    }

    /**
     * 借助Queue， Queue<TreeNode> queue = new LinkedList<>();
     * 来每一层offer入队 然后出队poll取出值 保存数据
     * @param root
     * @return
     */
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        //入队
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                //出队
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }

}


